// pages/add_work/add_work.js
const config = require('../../config.js');
const utils = require('../../utils/util.js');
const request = require('../../utils/request.js')
import { getCategoryList, addGoodsCb, getWorkDetail, getRecommendCount } from '../../static/api/api.js'
let cropperObj;
let app = new getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        category:'',
        pageStatus:'',
        goodsId:'',
        uploadImg:[],
        goodsData:{
            //分类
            category_id:'',
            //商品名称
            goods_name:'',
            //轮播图
            other_imgs:'',
            //主图
            main_img:'',
            //门市价
            price:'',
            //平台价
            grade_price:'',
            //图文详情
            description:'',
            //门店介绍
            abstract:'',
            //用户id
            store_user_id:'',
            //门店id
            store_id:'',
            //商品id
            goods_id:'',
            //服务耗时
            used_time:'',
            //保持天数
            days:'',
            //是否推荐
            is_recommend:'0'
        },
        uploadType: 1,
        cropperParams: {
            width: 350,
            height: 350,
            src: ''
        },
        isShowCropper: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        cropperObj = this.selectComponent("#imageCropper");
        let sid = app.globalData.memberInfo.store_id;
        let uid = options.store_user_id;
        if(options.store_user_id){
            sid=0;
        }else{
            uid = 0;
        }
        this.setData({
            'goodsData.store_id': sid,
            'goodsData.store_user_id':uid,
            'pageStatus': options.type || '',
            'goodsId':options.id || ''
        })
        if (options.type == 'edit' || options.type == 'reApply'){
            console.log('加载详情')
            this.getWorkDetail()
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        this.getCategoryList1()
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return app.onShareAppMessage()
    },
    goUrl(e) {
        utils.goNavigationUrl(e)
    },
    cancelClipBtn(){
        this.setData({
            'isShowCropper':false,
        })
        this.loadimage()
    },
    //获取项目详情
    getWorkDetail(){
        let that = this;
        wx.showLoading({
            title: '加载中',
        })
        getWorkDetail({goods_id:this.data.goodsId}).then(response => {
            wx.hideLoading()
            console.log(response.data)
            let arr = utils.formatImgArr(response.data.info.other_imgs)
            console.log(response.data.other_imgs)
            that.setData({
                'goodsData': response.data.info,
                'uploadImg':arr
            })
        }).catch(response => {
            wx.hideLoading()
            console.log(response)
        })
    },
    chooseImage(e) {
        let that = this;
        cropperObj=null
        cropperObj = this.selectComponent("#imageCropper");
        cropperObj.upload(function () {
            that.setData({
                'isShowCropper': true,
            })
        }, function () {
            that.setData({
                'isShowCropper': false,
            })
        });
        this.loadimage()
        that.setData({
            uploadType: 1
        })
    },
    clipCropperImg() {
        let that = this;
        console.log('裁剪的图片');
        wx.showLoading({
            title: '图片处理中...',
        })
        cropperObj.getImg(function (res) {
            wx.hideLoading()
            that.uploadImg(res.url, function (data) {
                console.log(data)
                if (that.data.uploadType == 1) {
                    that.setData({
                        'goodsData.main_img': data.data.url,
                        'isShowCropper': false
                    })
                } else if (that.data.uploadType == 2) {
                    that.data.uploadImg.push(data.data.url)
                    let images = that.data.uploadImg
                    console.log(images)
                    // 限制最多只能留下3张照片
                    that.setData({
                        uploadImg: images.length <= 3 ? images : images.slice(0, 3),
                        'isShowCropper': false
                    })
                }

            })
        })
    },
    cropperload(e) {
        console.log("cropper初始化完成");
    },
    loadimage(e) {
        cropperObj.imgReset();
    },
    //上传图片
    uploadImg(path, cb) {
        let that = this;
        setTimeout(function () {
            var urls = config.interfaceHost + "/api.php/common/Qiniu/upLoadImg";
            console.log(path);
            wx.showLoading({
                title: '加载中..',
            })
            wx.uploadFile({
                url: urls,
                filePath: path,
                name: 'image',
                header: {
                    'content-type': 'multipart/form-data',
                    'site': config.site,
                    'os': config.os,
                    'token': wx.getStorageSync('token')
                },
                success: function (res) {
                    wx.hideLoading()
                    var str = res.data;
                    console.log(res.data);
                    if (typeof cb == 'function') {
                        cb(JSON.parse(res.data));
                    }

                },
                fail: function (res) {
                    wx.hideLoading()
                    console.log(res);
                    wx.showModal({
                        title: '提示',
                        content: "网络请求失败，请确保网络是否正常",
                        showCancel: false,
                        success: function (res) {

                        }
                    });
                    wx.hideToast();
                }
            });
        }, 500)
    },
    inputValueChange(e) {
        utils.inputValueChange(e, this)
    },
    //获取分类数据
    getCategoryList1(){
        let that = this;
        console.log('加载分类')
        getCategoryList({}).then(response => {
            console.log('分类数据')
            wx.hideLoading()
            console.log(response.data)
            that.setData({
                'category': response.data.lists
            })
        }).catch(response => {
            wx.hideLoading()
            console.log('数据获取失败')
            console.log(response)
        })
    },
    //添加商品
    addGoodsCb(){
        let that = this;
        console.log('加载分类')
        this.setData({
            'goodsData.other_imgs':this.data.uploadImg.join(',')
        })
        if (this.data.pageStatus == 'edit') {
            
        } else {
            this.setData({
                'goodsData.goods_id':''
            })
        }
        wx.showLoading({
            icon:'none',
            title: '加载中...',
        })
        addGoodsCb(this.data.goodsData).then(response => {
            wx.hideLoading()
            if(this.data.pageStatus == 'edit'){
                wx.showToast({
                    icon: 'none',
                    title: '项目编辑成功。',
                })
            }else{
                wx.showToast({
                    icon: 'none',
                    title: '项目新增成功。',
                })
            }
            
            setTimeout(function(){
                let pages = getCurrentPages();
                let tarPage = pages[pages.length - 2];
                tarPage.setData({
                    'curStatus':1
                })
                tarPage.setData({
                    'curStatus': 0,
                    'pages.curPage': 1,
                    'pages.totalPage': 1,
                    'pageLoad': false,
                    'isNoMore': false,
                    'workList': null
                })
                tarPage.getStaffWorkList()
                wx.navigateBack({
                    
                })
            },1000)
        }).catch(response => {
            wx.hideLoading()
            console.log('数据获取失败')
            console.log(response)
        })
    },
    //切换门店
    changeCategory() {
        let itemArr = [];
        let that = this;
        this.data.category.forEach((el, index) => {
            itemArr[index] = el.category_name;
        })
        wx.showActionSheet({
            itemList: itemArr,
            success: function (res) {
                console.log(res.tapIndex)
                that.setData({
                    'goodsData.category_id': that.data.category[res.tapIndex].id
                })
            },
            fail: function (res) {
                console.log(res.errMsg)
            }
        })
    },
    uploadShopOtherImg() {
        let that = this;
        cropperObj = null
        cropperObj = this.selectComponent("#imageCropper");
        cropperObj.upload(function () {
            that.setData({
                'isShowCropper': true,
            })
        }, function () {
            that.setData({
                'isShowCropper': false,
            })
        });
        this.loadimage()
        that.setData({

            uploadType: 2
        })

    },
    //删除图片
    delImage(e) {
        let dataset = e.currentTarget.dataset;
        console.log(dataset)
        let images = this.data.uploadImg;
        images.splice(dataset.index, 1)
        this.setData({
            uploadImg: images
        })
    },
    //预览图片
    handleImagePreview(e) {
        const idx = e.target.dataset.index
        const images = this.data.uploadImg
        wx.previewImage({
            current: images[idx], //当前预览的图片
            urls: images, //所有要预览的图片
        })
    },
    //设置默认推荐
    setRecommentPro(){
        let that = this;
        let params={
            'store_id': this.data.goodsData.store_id,
            'store_user_id': this.data.goodsData.store_user_id,
        }
        wx.showLoading({
            title: '加载中...',
        })
        getRecommendCount(params).then((res)=>{
            wx.hideLoading()
            if(res.data.info<3){
                that.setData({
                    'goodsData.is_recommend': that.data.goodsData.is_recommend == 1 ? "0" : "1"
                })
            }else{
                wx.showToast({
                    icon:'none',
                    title: '您的封面项目已超过3个，请取消其他封面项目再进行操作',
                })
                that.setData({
                    'goodsData.is_recommend': 0
                })
               
            }
        }).then(res=>{
            wx.hideLoading()
        })
        
    }
})